import React from 'react';
import PositionedSentence from './model/PositionedSentence';
import { sentenceOperations } from './observable';
import { Subscription } from 'rxjs';
import ReactModal from 'react-modal';
import PositionedHanzi from './model/PositionedHanzi';
import { sentenceDB } from './SentenceStorage';

type SentenceListProps = {
  onSaveSentence?: (saveSentenceFn: (hanziList: PositionedHanzi[]) => void) => void;
  onClickSentence?: (sentence: PositionedSentence) => void;
};

type SentenceListState = {
  sentences: PositionedSentence[];
  showAddModal: boolean;
  remarkInputValue: string;
};
class SentenceList extends React.Component<SentenceListProps, SentenceListState> {
  private subscription: Subscription | null;

  constructor(props: SentenceListProps) {
    super(props);
    this.state = {
      sentences: [],
      showAddModal: false,
      remarkInputValue: '',
    };
    this.subscription = null;
  }

  componentDidMount(): void {
    this.load();
    this.subscription = sentenceOperations.subject.subscribe((signal) => {
      switch (signal) {
        case 'ADD':
          this.load();
          break;
        case 'REMOVE':
          this.load();
          break;
        default:
          throw new Error('TODO: 尚不支持');
      }
    });
  }

  componentWillUnmount(): void {
    this.subscription?.unsubscribe();
  }

  load = () =>
    (async () => {
      const sentences = await sentenceDB.searchSentences(''); // TODO: 放到 operations 中
      this.setState({ sentences });
    })();

  hideAddModal = () => this.setState({ showAddModal: false, remarkInputValue: '' });

  handleSaveSentence = () => {
    const { onSaveSentence } = this.props;
    const { remarkInputValue } = this.state;

    // TODO: 校验
    if (onSaveSentence) {
      const save = async (hanziList: PositionedHanzi[]) => {
        await sentenceOperations.addSentence({ hanziList, remark: remarkInputValue, createTime: Date.now() });
        this.hideAddModal();
      };
      onSaveSentence(save);
    } else {
      this.hideAddModal();
    }
  };

  handleDeleteSentence = (s: PositionedSentence) => {
    sentenceOperations.deleteSentenceByRemark(s.remark);
  };

  handleSentenceClicked = (sentence: PositionedSentence) => () => {
    const { onClickSentence } = this.props;
    if (onClickSentence) {
      onClickSentence(sentence);
    }
  };

  render(): React.ReactNode {
    const { sentences, showAddModal, remarkInputValue } = this.state;
    return (
      <div>
        <button onClick={(e) => this.setState({ showAddModal: true })}>保存排列</button>
        <ul>
          {sentences.map((s) => (
            <li key={s.remark} onClick={this.handleSentenceClicked(s)}>
              {s.remark} <span onClick={(e) => this.handleDeleteSentence(s)}>❌</span>
            </li>
          ))}
        </ul>
        <ReactModal isOpen={showAddModal} appElement={document.createElement('div')}>
          <input
            value={remarkInputValue}
            onChange={(e) => this.setState({ remarkInputValue: e.target.value })}
            placeholder="xxxx"
          />
          <button onClick={this.handleSaveSentence}>保存</button>
        </ReactModal>
      </div>
    );
  }
}

export default SentenceList;
